/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup  分类
 * @api {POST} api/category/create 新加分类
 * @apiName api/category/create
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/category/create', {
 *    storeID: '店铺ID',
 *    kind: '分类级别',
 *    name: '分类名称',
 *    parentID: '父级分类ID'
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {number} storeID 店铺ID
 * @apiParam {number} kind 1: 一级分类， 2: 二级分类
 * @apiParam {string} name 分类名称
 * @apiParam {number} parentID Kind 为 1 时无意义，Kind 为 2 时是父级分类的 ID
 * @apiSuccess (请求成功) {Object} category 分类数据
 * @apiuse  ErrorResponse
 */


const { query, create } = require('../../helper/db');
const { ok, door, now } = require('../../helper/util');

module.exports = async ctx => {
  var params = ctx.request.body;
  var token = ctx.headers.authorization;
  var user = await door(token);
  var storelist = await query('select * from store where name = ?', [params.name]);

  var parentID = params.parentID ? params.parentID : 0;

  if (storelist.length) {
    throw new Error('该分类已存在');
  }

  var category = await create('category', {
    name: params.name,
    kind: params.kind,
    parentid: parentID,
    storeID: params.storeID,
    createdat: now()
  });

  ctx.body = ok({ category });
}
